#!/usr/bin/perl
#
#Check HOME
# Este script fara um check na home, verificando integridade de links de diversas urls da home. 

use strict ;
use IO::Socket;
use File::Basename;
use Sys::Hostname;
use Fcntl ':flock';


my $url = shift();
my $remote_host = "";
my $remote_dir = "";
my $remote_port = 80 ;

my $logDate = `/bin/date +%Y%m%d`;
chomp $logDate ;

my $errorLog = "/export/logs/check/monit_urls-${logDate}.log";


my $hostname .= "check_url.adm.uol.intranet";
my $scriptname=basename("$0");

my %urls = ();
my %timeouts = ();

my $statusOK = 0;
my $statusWarning = 1;
my $statusCritical = 2;

sub timestamp
{
    my $tstamp = "[". time()."]";

    return ( $tstamp );
}

sub printResult ()
{
   my $msg = shift();
  
   my $tstamp = timestamp();

   my $urlname = $url;
   $url =~ s/\///g;
   my $message = "$tstamp PROCESS_SERVICE_CHECK_RESULT;$hostname;CheckURL $url;$msg";

   my $out = `/bin/logger -p local5.info \"$message\"`;

   open ( ERRORLOG, ">>$errorLog" ) or die "Can't write to file: $!";
   flock ( ERRORLOG, LOCK_EX );
   print  ERRORLOG "$message\n";
   flock ( ERRORLOG, LOCK_UN );
   close ( ERRORLOG );

   #print "$message\n";
}

sub abortResult ()
{
   my $msg = shift();

   my $tstamp = timestamp();


   my $message = "$tstamp PROCESS_SERVICE_CHECK_RESULT;$hostname;Check Full URL;$msg";

   #my $out = `/bin/logger -p local5.info \"$message\"`;

   #open ( ERRORLOG, ">>$errorLog" ) or die "Can't write to file: $!";
   #print  ERRORLOG "$message";
   #close ( ERRORLOG );

   print "$message\n";
   die "$message\n";
}


if ( ! defined $url || $url !~ /[\w|\-|\d]+\.[\w|\-|\d]+\.[\w|\-|\d]+/ )
{
   print "Usage: $0 <url>\n";
   exit;
}

if ( $url =~ /([\w|\-|\d|\.]+)\/([\w|\.|\/|\d|\_|\-]+)/ )
{
   $remote_host = $1 ;
   $remote_dir = $2 ;
   print "$remote_dir \n";
}
elsif ( $url =~ /([\w|\-|\d|\.]+)/ )
{
   $remote_host = $1 ;
   $remote_dir = "" ;
}

my $socket = IO::Socket::INET->new(PeerAddr => $remote_host,                                
                                               PeerPort => $remote_port,                                
					       Proto    => "tcp",                                
					       Type     => SOCK_STREAM)    
      or &abortResult("$statusCritical;Couldn't connect to $remote_host:$remote_port : $@");
      
print $socket "GET /$remote_dir HTTP/1.0\nHOST: $remote_host\n\n";

my $setMenu = 0; 

while ( <$socket> )
{
    my $line = $_ ;
    #print $line ;

    #if ( $line =~ /noticias_mediotexto2_cham/ )
    #{
       #print $line ;
    #}

    if ( $line =~ /function uolbarCombo\(\)/ )
    {
       $setMenu = 1;
    }

    if ( $setMenu == 1 )
    {
         if ( $line =~ /\'([\w|\d|\.|\/]+)'\,\'/ )
	 {
	     my $url = $1 ; 
 
             if ( $url !~  /^http/ )
             {
                $url = "http://$url";
             }

             #print "URL $url\n";

	     if ( ! exists $urls{$url} )
	     {
	         $urls{$url} = 1 ;
	     }
	 }


	 if ( $line =~ /\)\;/ )
	 {
	     $setMenu = 0;
	 }
	 next ;
    }

    next if ( $line =~ /(http:\/\/click\.uol\.com\.br\/.*\&u\=[\"|\s|\>|\|]{1})/ || $line =~ /(http:\/\/click\.uol\.com\.br\/.*\&amp\;u\=[\"|\s|\>|\|]{1})/ );

    if ( $line =~ /http:\/\/click\.uol\.com\.br\/.*\&u\=([\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#|\%]+)[\"|\s|\>|\|]{1}/ )
    {
       my $url = $1;

       next if ( $url !~ /http:\/\/[\w|\d|\-]+\.[\w|\d|\-]+\..*/ );

       if ( $url =~ /(http:\/\/.*)\|http:\/\// )
       {
             $url = $1 ;
       }

       if ( $url !~  /clicklogger\.rm/ and $url !~ /^https/ )
       {
          #print "URL $url\n";
	  if ( ! exists $urls{$url} )
	  {
	      $urls{$url} = 1 ;
	  }
       }
    }
    elsif ( $line =~ /http:\/\/click\.uol\.com\.br\/.*\&amp\;u\=([\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#|\%]+)[\"|\s|\>|\|]{1}/ )
    {
       my $url = $1;

       #print "URL $url\n";

       next if ( $url !~ /http:\/\/[\w|\d|\-]+\.[\w|\d|\-]+\..*/ );

       if ( $url =~ /(http:\/\/.*)\|http:\/\// )
       {
             $url = $1 ;
       }

       if ( $url !~  /clicklogger\.rm/ and $url !~ /^https/ )
       {
          #print "URL $url\n";
          if ( ! exists $urls{$url} )
          {
              $urls{$url} = 1 ;
          }
       }
    }
    elsif ( $line =~ /href\=\"(http\:[\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#|\%]+)[\"|\s|\>|\|]{1}/ )
    {
       my $url = $1 ;
       if ( $url !~ /javascript/ and  $url !~ /bn\.uol\.com\.br/ and $url !~ /clicklogger\.rm\.uol\.com\.br/ and $url !~ /www2\.uol\.com\.br/ and $url !~ /esporte\.uol\.com\.bri\/{1,2}v4\// )
       {
          #print "URL $url\n";
	  if ( ! exists $urls{$url} )
	  {
	      $urls{$url} = 1 ;
	  }
       }
    }
    elsif ( $line =~ /href\=(http\:[\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#|\%]+)[\"|\s|\>|\|]{1}/ )
    {
       my $url = $1 ;
       if ( $url !~ /javascript/ and  $url !~ /bn\.uol\.com\.br/ and $url !~ /clicklogger\.rm\.uol\.com\.br/ and $url !~ /www2\.uol\.com\.br/  and $url !~ /esporte\.uol\.com\.br\/{1,2}v4\// )
       {
          #print "URL $url\n";
	  if ( ! exists $urls{$url} )
	  {
	      $urls{$url} = 1 ;
	  }
       }
    }
    elsif ( $line =~ /href\=\"([\w|\=|\:|\.|\&|\?|\/|\-|\;|\_|\#|\%]+)[\"|\s|\>|\|]{1}/ )
    {
       my $url = "http://$remote_host/$1" ;
       if ( $url !~ /javascript/ and  $url !~ /bn\.uol\.com\.br/ and $url !~ /clicklogger\.rm\.uol\.com\.br/ and $url !~ /www2\.uol\.com\.br/ and $url !~ /esporte\.uol\.com\.br\/{1,2}v4\// )
       {
          #print "URL $url\n";
          if ( ! exists $urls{$url} )
          {
                $urls{$url} = 1 ;
          }
       }
    }
}
close($socket);

my $isOk = 0; 
my $failMessage = "";

## Alterado (20080730)
my $uri; my $hostname;

foreach my $url (keys %urls )
{
   #print "URL $url\n";
## Alterado (20080730)
   #$url =~ /http\:\/\/([\w|\-|\_|\.]+)(\/.*)/ ;
   #my $hostname = $1 ;
   #my $uri = $2 ;

   if ($url =~ /http\:\/\/([\w|\-|\_|\.]+)(\/.*)/){
	$hostname = $1 ;
	$uri = $2 ;
   } else {next}


   next if ( exists ($timeouts{$hostname}) );
   next if ( $uri =~ /\.gif/  or $uri =~ /\.jpg/ );

   if ( $uri =~ /(.*)\|/ )
   {
       $uri = $1 ;
   }

   my $remote_host = $hostname;
   my $remote_port = 80 ;

   my $socket = IO::Socket::INET->new(PeerAddr => $remote_host,
                                                  PeerPort => $remote_port,
						  Proto    => "tcp",
						  Type     => SOCK_STREAM,
						  Timeout => 10 )
   or my $failure  =  "$@"; 
   
   if ( $failure  )
   {
      if ( ! exists ($timeouts{$hostname}) )  
      {
          $timeouts{$hostname} = 1 ;
          $isOk = 1;
          $failMessage .= "( Error Connecting to $hostname $failure )" ; 
      }
      next ;
   }



   if ( $hostname =~ /portalimprensa\.uol\.com\.br/ || 
        $hostname =~ /www1\.uol\.com\.br/ || 
        $hostname =~ /carsale\.uol\.com\.br/ || 
        $hostname =~ /www2\.uol\.com\.br/ ||
        $hostname =~ /prouni\-inscricao\.mec\.gov\.br/ ||
        $hostname =~ /abiliodiniz\.uol\.com\.br/ ||
        $hostname =~ /edicaodigital\.folha\.com\.br/ 
      )

   {
        print $socket "GET $uri HTTP/1.1\nUser-Agent: checkURL\nHOST: $hostname\n\n";
   }
   else
   {
        print $socket "HEAD $uri HTTP/1.1\nUser-Agent: checkURL\nHOST: $hostname\n\n";
   }

   my $redirect = 0 ;

   while ( <$socket> )
   {
      my $response = $_ ;
      #print "$response\n";
      if ( $response =~ /HTTP\/1.1 200 OK/ )
      {
        #&printResult( "OK hostname \"$hostname$uri\"");
	last ;
	close($socket);
      }
      #elsif ( $response =~ /HTTP\/1.1 30[1|2|7]\s/ )
      elsif ( $response =~ /HTTP\/1.1 [3|4]0[1|2|4|7|0]\s/ )
      {
	 close($socket);
         $redirect = 1 ;
	 #print "REDIRECT\n$response\n";
      }
      elsif ( $response =~ /HTTP\/1.1 (\d+)\s/ )
      {
          my $code = $1 ;
          $isOk = 1;
          $failMessage .= "( HTTP ERROR CODE $code for host:  ${hostname}$uri )" ; 
      }

      if ( $redirect == 1 and $response =~ /Location: (.*)/ )
      {
         my $location = $1 ;
	 if ( $location =~ /e.busca.uol.com.br/ )
	 {
            $isOk = 1;
            $failMessage .= "( HTTP ERROR CODE 302 for host: ${hostname}$uri - $location )" ; 
	 }
	 last ;
      }
   }
   close($socket);
}

if ( $isOk == 0 )
{
   &printResult ("$statusOK; CheckURL: $remote_host/$remote_dir - Everything is fine");
}
else
{
   &printResult ( "$statusCritical; CheckURL: $failMessage" );
}
